package com.museyu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserSessionService {
    
    private static final String USER_SESSION_PREFIX = "user:session:";
    private static final long SESSION_TIMEOUT = 24; // 会话超时时间（小时）
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 创建新的用户会话
     * @param playerId 玩家ID
     * @return 会话ID
     */
    public String createSession(String playerId) {
        String sessionId = UUID.randomUUID().toString();
        String key = USER_SESSION_PREFIX + sessionId;
        redisTemplate.opsForValue().set(key, playerId, SESSION_TIMEOUT, TimeUnit.HOURS);
        return sessionId;
    }
    
    /**
     * 获取会话对应的玩家ID
     * @param sessionId 会话ID
     * @return 玩家ID，如果会话不存在则返回null
     */
    public String getPlayerId(String sessionId) {
        String key = USER_SESSION_PREFIX + sessionId;
        Object value = redisTemplate.opsForValue().get(key);
        return value != null ? value.toString() : null;
    }
    
    /**
     * 更新会话超时时间
     * @param sessionId 会话ID
     */
    public void refreshSession(String sessionId) {
        String key = USER_SESSION_PREFIX + sessionId;
        redisTemplate.expire(key, SESSION_TIMEOUT, TimeUnit.HOURS);
    }
    
    /**
     * 删除会话
     * @param sessionId 会话ID
     */
    public void removeSession(String sessionId) {
        String key = USER_SESSION_PREFIX + sessionId;
        redisTemplate.delete(key);
    }
} 